package com.dq.health.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dq.health.dto.request.user.QueryUserParam;
import com.dq.health.dto.request.user.SaveUserRequest;
import com.dq.health.dto.request.user.UpdatePasswordRequest;
import com.dq.health.dto.request.user.UserIdRequest;
import com.dq.health.dto.response.user.UserDetail;
import com.dq.health.entity.user.UserBaseInfo;
import com.dq.health.exception.BizRtException;
import com.dq.health.security.PasswordEncryService;
import com.dq.health.service.IAPIMenuService;
import com.dq.health.service.IAPIRoleService;
import com.dq.health.service.IAPIUserService;
import com.dq.health.utils.RandomCodeUtil;
import com.dq.health.utils.SecurityUtils;
import com.dq.health.utils.data.JsonUtil;
import com.dq.health.utils.view.SimpleView;
import com.dq.health.utils.view.StringView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    private @Autowired IAPIUserService userService;

    private @Autowired IAPIMenuService menuService;

    private @Autowired PasswordEncryService passwordEncryService;

    private @Autowired IAPIRoleService roleService;

    @PostMapping(value = "/getInfos")
    @ApiOperation("获取当前用户信息")
    public SimpleView<UserDetail> getInfos() {
        LOGGER.info("### 获取当前用户信息 start");
        SimpleView<UserDetail> view = new SimpleView<>();
        Long userId = SecurityUtils.getLoginUserId();
        if (userId == null) {
            return view;
        }

        UserDetail userDetail = userService.queryUserDetail(userId);
        view.success(userDetail);
        return view;
    }

    @PostMapping(value = "/updatePassword")
    @ApiOperation("修改自身密码")
    public StringView updatePassword(@RequestBody @Valid UpdatePasswordRequest req) {
        LOGGER.info("### 修改自身密码 start");
        StringView view = new StringView();
        String oldPassword = req.getOldPassword();
        String newPassword = req.getNewPassword();

        Long loginUserId = SecurityUtils.getLoginUserId();
        if (loginUserId == null) {
            view.fail("请先登陆");
            return view;
        }

        // 验证密码
        UserBaseInfo userBaseInfo = userService.queryUserById(loginUserId);
        boolean matches = passwordEncryService.matches(oldPassword, userBaseInfo.getPassword());
        if (!matches) {
            view.fail("密码错误");
            return view;
        }

        // 修改密码
        String newPasswordCode = passwordEncryService.encode(newPassword);
        userService.updatePassword(loginUserId, newPasswordCode);
        view.success("修改成功");
        return view;
    }

    @PostMapping(value = "/updateSelfUserInfo")
    @ApiOperation("修改自身用户信息")
    public StringView updateSelfUserInfo(@RequestBody SaveUserRequest request) {
        LOGGER.info("### 修改自身用户信息 start req:{}", JsonUtil.toString(request));
        StringView view = new StringView();

        Long loginUserId = SecurityUtils.getLoginUserId();
        request.setUserId(loginUserId);
        userService.updateUserInfo(request);

        view.success("修改成功");
        return view;
    }

    @PostMapping(value = "/addUser")
    @ApiOperation("新增用户")
    public StringView addUser(@RequestBody SaveUserRequest request) {
        StringView view = new StringView();

        Long userId = userService.addUser(request);
        view.success(userId.toString());

        return view;
    }

    @PostMapping(value = "/queryUserInfo")
    @ApiOperation("查询用户信息")
    public SimpleView<UserDetail> updateUserInfo(@RequestBody @Valid UserIdRequest req) {
        LOGGER.info("### 查询用户信息 start");
        SimpleView<UserDetail> view = new SimpleView<>();
        Long userId = req.getUserId();

        UserDetail userDetail = userService.queryUserDetail(userId);
        view.success(userDetail);

        return view;
    }

    @PostMapping(value = "/updateUserInfo")
    @ApiOperation("修改用户信息")
    public StringView updateUserInfo(@RequestBody SaveUserRequest request) {
        LOGGER.info("### 修改用户信息 start");
        StringView view = new StringView();
        userService.updateUserInfo(request);
        view.success("修改成功");
        return view;
    }

    @PostMapping(value = "/updateUserStatus")
    @ApiOperation("修改用户状态")
    public StringView updateUserStatus(@RequestBody SaveUserRequest request) {
        LOGGER.info("### 修改用户状态 start");
        StringView view = new StringView();

        Long userId = request.getUserId();
        Integer userStatus = request.getUserStatus();
        Assert.notNull(userId, "userId cant be null");
        Assert.notNull(userStatus, "userStatus cant be null");

        SaveUserRequest updateSysUser = new SaveUserRequest();
        updateSysUser.setUserId(userId);
        updateSysUser.setUserStatus(userStatus);
        userService.updateUserInfo(updateSysUser);

        view.success("修改成功");
        return view;
    }

    @PostMapping(value = "/resetPassword")
    @ApiOperation("重置密码")
    public StringView resetPassword(@RequestBody @Valid UserIdRequest request) {
        LOGGER.info("### 重置密码 start");
        StringView view = new StringView();

        Long userId = request.getUserId();
        UserBaseInfo userBaseInfo = userService.queryUserById(userId);
        if (userBaseInfo == null) {
            throw new BizRtException("用户不存在！");
        }

        String initPassword = RandomCodeUtil.generateInitPassword(8);
        userService.updatePassword(userId, passwordEncryService.encode(initPassword));

        view.success("重置成功");
        return view;
    }

    @PostMapping(value = "/getUserList")
    @ApiOperation("查询用户列表")
    public SimpleView<IPage<UserDetail>> getUserList(@RequestBody QueryUserParam request) {
        LOGGER.info("### 查询用户列表 start");
        SimpleView<IPage<UserDetail>> view = new SimpleView<>();

        IPage<UserDetail> userBaseInfoIPage = userService.queryUserList(request);

        view.success(userBaseInfoIPage);
        return view;
    }
}
